<template>
<div :class="[disabled?'':'bd']" >
  <div class="flex w100" style="width: 100%;height: 28px;"  >
    <div class="sel">
      {{ modelValue }}
    </div>
    <div class="ml5 mt5" style="font-size: 13px;" v-if="!disabled">
      <j-space>
        <span v-if="showYe" class="btnspan" @click="chose" style="font-size: 13px;">余额（<span style="color: #1e9fff;">{{ye}}</span>）</span>
        <span class="btnspan" v-if="showGoods" @click="chose1">商品</span>
      </j-space>
    </div>
  </div>

<!--  <tiny-dialog-box v-model:visible="show1" draggable style="width: 1100px;" title="预收商品列表">-->
<!--    <j-grid :fields="cols1" v-model="list" :height="500" :show-page="false" @edit-closed="editClose1" />-->
<!--    <div class="mt10">-->
<!--      <JButton   type="info" @click="confirm1" style="height: 40px;width: 150px;">确定</JButton >-->
<!--    </div>-->
<!--  </tiny-dialog-box>-->
</div>
</template>
<script setup>
import tool from "@/utils/tool";

import {ref, computed} from "vue";
import {TinyDialogBox} from "@opentiny/vue";
const emit = defineEmits(['change'])
const props = defineProps({
  modelValue: {type: [String, Number], default: ''},
  size: {type: [String, Number], default: 'small'},
  width: {type: [String, Number], default: ''},
  disabled: {type: Boolean, default: false}, // 是否搜索模式
  readonly: {type: Boolean, default: true}, // 是否搜索模式
  showYe: {type: Boolean, default: false}, // 显示预收金额
  showGoods: {type: Boolean, default: false}, // 显示预收商品
})
const model = defineModel()
const ye = defineModel('ye')
const ye1 = defineModel('ye1')
const fApi = ref({})
const amount = ref()
const list = ref([])
const show = ref(false)
const show1 = ref(false)
const tp = ref('')

const cols = computed(() => {
  return [
    {type: 'index', width: 30},
    {field: 'buName', title: tp.value===150501? '供应商':'客户', width: 180,},
    {field: 'billDate', title: '日期', width: 90,align: 'center'},
    {field: 'transTypeName', title: '类型', width: 100,align: 'center'},
    {field: 'billNo', title: '票号', width: 110, canClick: true},
    {
      field: 'leftAmount', title: tp.value===150501? '预付结余':'预收结余', width: 150, align: 'right', sum: true,
      formatter:'formatMoney'
    },
    {field: 'hxAmount', title: '本次核销', width: 90, align: 'right', sum: true,
      editor: 'JInput'
    },
  ]
})
const cols1 = computed(() => {
  return [
    {type: 'index', width: 50},
    {field: 'invName', title: '商品', width: 220,},
    {field: 'billDate', title: '日期', width: 100,align: 'center'},
    {field: 'billNo', title: '票号', width: 100, canClick: true},
    {field: 'qty', title: '总数量', width: 80, align: 'right', sum: true},
    {field: 'unit', title: '单位', width: 60, align: 'right', sum: true},
    {field: 'price', title: '结余单价', width: 80, align: 'right', sum: true},
    {field: 'leftAmount', title: '结余金额', width: 80, align: 'right', sum: true},
    {field: 'leftQty', title: '结余数量', width: 80, align: 'right', sum: true},
    {
      field: 'hxQty', title: '本次核销数量', width: 110, align: 'right', sum: true,
      editor: 'JInput'
    },
  ]
})
const transType = computed(() => {
  return fApi.value.getValue('transType')
})
const height = computed(() => {
  if(props.size === 'small') return 32
  return 38
})
// 弹出选择 预收款，预付款
const setApi = (api) => {
  fApi.value = api
}
const cellClick =  ({row})  => {
  row.checked = !row.checked
}
const editClose  = (cell)  => {
  cell.row[cell.column.property] = tool.xe.toNumber(cell.row[cell.column.property])
}
const editClose1  = (cell)  => {
  cell.row[cell.column.property] = tool.xe.toNumber(cell.row[cell.column.property])
}
const editorApi = ref()
const chose =  ()  => {
  if(tool.xe.isEmpty(fApi.value)) {
    return  tool.err('选择失败')
  }
  if(tool.xe.toNumber(ye.value) === 0) {
    return tool.err('余额为 0 ')
  }
  list.value = []
  tp.value = fApi.value.getValue('transType')
  let buId = fApi.value.getValue('buId')
  let transType = fApi.value.getValue('transType')
  let billId = fApi.value.getValue('id')
  if(!buId) return tool.err('没有选择' + (transType === 150601 ?'客户':'供应商'))
  if(!transType) return tool.err('业务类型不明确')
  tool.post('bill/getYsfList', {
    billId: billId,
    buId: buId,
    transType: transType
  }, true).then(ret => {
    if(ret.stat) {
      list.value = ret.data
      let chosedList = fApi.value.getValue('dikouList')
      if(list.value.length === 0) {
        list.value = chosedList
      }
      else {

      }
      for (let i = 0; i < list.v; i++) {

      }
      let options = {
        title: tp.value === 150501?'预付抵扣':'预收抵扣',
        width: 900,
        height: 550,
        mounted: (api) => { editorApi.value = api},
        rules: [
          {
            field: 'ysGrid', com: 'JGrid', columns: cols.value,width: 850, height: 500,
            passList: list.value,editable: true,bindData: true
          }
        ],
        btns: [
          {
            name: '确定', click: (api, close) => {
              options.confirm(close)
            }
          }
        ],
        confirm: (close) => {
          let lists = editorApi.value.getValue('ysGrid')
          let selectList = lists.filter(row => {
            row.hxAmount = tool.xe.toNumber(row.hxAmount)
            row.leftAmount = tool.xe.toNumber(row.leftAmount)
            return row.hxAmount !== 0
          })
          for (let i = 0; i < selectList.length; i++) {
            if(selectList[i].leftAmount > 0) {
              if(selectList[i].hxAmount<0) {
                return tool.err('本次核销不能小于0')
              }
              if(selectList[i].hxAmount > selectList[i].leftAmount) {
                return tool.err(`第${i+1}行 核销金额大于结余`)
              }
            }
            else {
              if(selectList[i].hxAmount>0) {
                return tool.err('本次核销不能大于0')
              }
              if(selectList[i].hxAmount < selectList[i].leftAmount) {
                return tool.err(`第${i+1}行 核销金额大于结余`)
              }
            }
          }
          let amount = tool.xe.sum(selectList, 'hxAmount')
          model.value = amount
          setTimeout(()=>{
            emit('change', fApi.value,{
              type: 'ysk',
              amount: amount,
              list: selectList
            })
            close()
          },1)
        }
      }
      tool.editor(options)
    }
  })
}
const chose1  = ()  => {
  list.value = []
  if(!tool.xe.isEmpty(fApi.value)) {
    let ysList = fApi.value.exec('infos', 'getData')
    let buId = fApi.value.getValue('buId')
    let transType = fApi.value.getValue('transType')
    let billId = fApi.value.getValue('id')
    let ys = ysList.filter(row => {
      return !!row.ysId
    })
    if(!buId) return tool.err('没有选择' + (transType === 150601 ?'客户':'供应商'))
    if(!transType) return tool.err('业务类型不明确')
    tool.post('bill/getYsgList', {
      billId: billId,
      buId: buId,
      transType: transType
    }).then(ret => {
      if(ret.stat) {
        let arr = []
        if(ys.length > 0) {

        }
        else if(ret.data.length > 0) {

        }
        let options = {
          title: '预收商品列表',
          width: 1100,
          height: 550,
          mounted: (api) => { editorApi.value = api},
          rules: [
            {
              field: 'ysGrid', com: 'JGrid', columns: cols1.value,width: 1050, height: 500,
              passList: list.value,editable: true,bindData: true
            }
          ],
          btns: [
            {
              name: '确定', click: (api, close) => {
                options.confirm(close)
              }
            }
          ],
          confirm: (close) => {
            let lists = editorApi.value.getValue('ysGrid')
            let selectList = lists.filter(row => {
              row.hxAmount = tool.xe.toNumber(row.hxAmount)
              row.leftAmount = tool.xe.toNumber(row.leftAmount)
              return row.hxAmount !== 0
            })
            for (let i = 0; i < selectList.length; i++) {
              if(selectList[i].leftAmount > 0) {
                if(selectList[i].hxAmount<0) {
                  return tool.err('本次核销不能小于0')
                }
                if(selectList[i].hxAmount > selectList[i].leftAmount) {
                  return tool.err(`第${i+1}行 核销金额大于结余`)
                }
              }
              else {
                if(selectList[i].hxAmount>0) {
                  return tool.err('本次核销不能大于0')
                }
                if(selectList[i].hxAmount < selectList[i].leftAmount) {
                  return tool.err(`第${i+1}行 核销金额大于结余`)
                }
              }
            }
            let amount = tool.xe.sum(selectList, 'hxAmount')
            model.value = amount
            setTimeout(()=>{
              emit('change', fApi.value,{
                type: 'ysk',
                amount: amount,
                list: selectList
              })
              close()
            },1)
          }
        }
        tool.editor(options)

        // ret.data.map(row => {
        //   ys.map(y => {
        //     if(row.ysId === y.ysId)
        //       row.hxQty = y.qty
        //   })
        //   list.value.push(row)
        // })
        // show1.value = true
      }
    })
  }

}
const confirm1 =  () =>  {
  let list = list.value.filter(row => {
    return tool.xe.toNumber(row.hxQty) !== 0
  })
  let amount = 0
  for (let i = 0; i < list.length; i++) {
    let row = list[i]
    row.sub = tool.multiply(row.hxQty,row.price)
    amount = tool.add(amount, row.sub)
    if(row.hxQty > row.leftQty)
      return tool.warning('核销数据大于结余')
  }

  model.value = amount
  setTimeout(()=>{
    emit('change', {
      type: 'ysg',
      amount: amount,
      list: list
    })
  },1)
  show.value1 = false
}



defineExpose({setApi})
</script>
<style lang="scss" scoped>
.sel {
  flex: 1;text-align: left;padding-left: 5px;color: #656D78;height: 28px;line-height: 28px;
  border-bottom: 1px solid rgba(0,0,0,0.3);
}
.btnspan {
  &:hover {
    cursor: pointer;
    color: #1e9fff;
  }
}
.bd {
  //border: 1px solid;
  //border-color: var(--ti-common-color-border);
  width: 100%;
}

</style>